<template>
	<view class="clothing-recycle">
		<!-- #ifdef H5 -->
		<custom-navbar title="旧衣回收" />
		<!-- #endif -->
		<view class="recycle-top d-flex justify-content-center align-items-center">
			<image src="https://image.chushouya.com/assets/images/recycle/img_fl.png" mode="widthFix"></image>
		</view>
		<view class="recycle-info">
			<!-- Pickup Information -->
			<view class="pickup-section">
				<view class="section-title">上门取件回收</view>

				<view class="form-item" @click="handleShipping">
					<text class="form-label">取件地址</text>
					<view class="form-value d-flex justify-content-between align-items-center">
						<text class="text" :class="{ placeholder: !addressInfo.address }">
							{{ addressInfo.address || "请选择取件地址" }}
						</text>
						<image class="arrow-icon"
							src="https://image.chushouya.com/assets/images/product/icon_click@2x.png"
							mode="aspectFill" />
					</view>

				</view>


				<view class="form-item" @click="selectTime">
					<text class="form-label">上门时间</text>
					<view class="form-value d-flex justify-content-between align-items-center">
						<text class="text" :class="{ placeholder: !appointTime }">
							{{ appointTime || "请选择取件时间" }}
						</text>
						<image class="arrow-icon"
							src="https://image.chushouya.com/assets/images/product/icon_click@2x.png"
							mode="aspectFill" />
					</view>
				</view>
			</view>

			<!-- Weight Estimation -->
			<view class="weight-section">
				<view class="section-title">预估重量</view>
				<view class="weight-options d-flex justify-content-between align-items-center">
					<view v-for="(option, index) in weightOptions" :key="index"
						class="weight-option d-flex flex-column justify-content-center align-items-center"
						:class="{ active: selectedWeight == index }" @click="selectedWeight = index">
						<view class="weight-range">{{ option.range }}</view>
						<view class="weight-price">{{ option.price }}</view>
						<view class="weight-note" v-if="option.note">{{
							option.note
						}}</view>
					</view>
				</view>

				<!-- Environmental Impact -->
				<view class="environmental-impact">
					<image class="eco-icon" src="https://image.chushouya.com/assets/images/recycle/icon_hb.png"
						mode="aspectFill" />
					<text class="impact-text">1kg旧衣≈<text>5.35kg</text>碳排放量，<text>0.27m³</text>绿化</text>
				</view>
			</view>
		</view>
		<view class="fixed-footer">
			<view class="btn" @click="submitRecycle">确认提交</view>
		</view>
		<select-time-layer ref="selectTimeRef" :time="time" :multiArray="timeMultiArray"
			:serviceTypeText="serviceTypeText" @handleDaysClick="handleDaysClick"
			@handleHoursClick="handleHoursClick" />
		
		<!-- 提交成功 -->
		<order-layer ref="orderRef" @handleOrder="handleOrder" />
	</view>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import SelectTimeLayer from "../assess/components/SelectTimeLayer.vue";
import OrderLayer from "../assess/components/OrderLayer.vue";
import regionTree from '@/utils/city.json'
import StringUtil from '@/utils/stringUtil'
import {
	parseTime, waitShowToast,
	wait, generateVisitTime
} from '@/utils';
import {
	createClothesRecycleOrder
} from "@/api";
export default {
	components: {
		SelectTimeLayer,
		OrderLayer,
	},
	data() {
		return {
			orderData: {},
			openId: "",
			addressInfo: {
				province: "",
				city: "",
				district: "",
				districtCode: 0,
				address: "",
				userName: "",
				userPhone: "",
			},
			treeMap: { text: "label", value: "value" },
			address: "",
			gegionTree: [],
			selectedAddress: "",
			// appointTime: "",
			selectedWeight: 0,
			weightOptions: [{
				range: "3-10kg",
				price: "约20件",
				value: "3-10kg",
			},
			{
				range: "10-20kg",
				price: "约40件",
				value: "10-20kg",
			},
			{
				range: "20-50kg",
				price: "约60件",
				value: "20-50kg",
			},
			{
				range: "50kg以上",
				price: "约150件",
				note: "需拍照审核",
				value: "50kg+",
			},
			],
			time: [],
			timeMultiArray: [
				["0", "1", "2", "3", "4", "5"],
				["08", "10", "12", "14", "16", "18"],
			],
		};
	},
	computed: {
		...mapGetters([
			'systemInfo', 'userInfo', 'location', 'geoLocation',
			'channel', 'recoveryMode'
		]),
		serviceTypeText() {
			const text = this.wayIndex == 0 ? '取件' : '上门'
			return text
		},
		appointTime: function () {
			return StringUtil.format("{} {}:00 - {}:00", parseTime(this.time[0], "{m}月{d}日 (周{a}) "), parseInt(this.time[1]), parseInt(this.time[1]) + 2);
		}
	},
	async created() {
		this.generateTime()
		this.handleGetOpenId()
	},
	methods: {
		//获取用户openId
    async handleGetOpenId() {
      const result = await loadOpenid()
      if (result.code === 200) {
        this.openId = result.data
      }
    },
		//创建时间
		generateTime() {
			this.timeMultiArray = generateVisitTime()
			this.time = [this.timeMultiArray[0].day, this.timeMultiArray[0].hour[0]]
			// this.$emit('handleTime', this.time)
		},
		// 获取定位
		async getLocation() {
			try {
				uni.showLoading({ title: '加载中', mask: false })

				let geoLocation = this.geoLocation
				if (!geoLocation.province) {
					const res = await this.$store.dispatch('userLocation/getLocation', true)
					if (res.code == -1) {
						const res = await this.$store.dispatch('userLocation/loadGeoLocation', true)
					}
					if (res.geoLocation && res.geoLocation.province) {
						geoLocation = res.geoLocation
					}
				}
				console.log("=============>", geoLocation)
				if (geoLocation.province) {
					this.addressInfo.districtCode = geoLocation.districtCode || 0,
						this.addressInfo.province = geoLocation.province || '',
						this.addressInfo.city = geoLocation.city || '',
						this.addressInfo.district = geoLocation.district || '',
						this.addressInfo.districtCode = geoLocation.adCode || '',
						this.addressInfo.address = geoLocation.address || ''
					// this.loadRecycleMethod()
				}
			} finally {

			}
		},
		// 根据省市区名称从regionTree中获取对应的value（代码）
		getRegionCodes(provinceName, cityName, districtName) {
			let provinceCode = null;
			let cityCode = null;
			let districtCode = null;

			// 查找省份
			const province = regionTree.find(item => item.label === provinceName);
			if (province) {
				provinceCode = province.value.padEnd(6, '0');

				// 查找城市
				if (province.children && cityName) {
					const city = province.children.find(item => item.label === cityName);
					if (city) {
						cityCode = city.value.padEnd(6, '0');

						// 查找区县
						if (city.children && districtName) {
							const district = city.children.find(item => item.label === districtName);
							if (district) {
								districtCode = district.value.padEnd(6, '0');
							}
						}
					}
				}
			}

			return {
				provinceCode,
				cityCode,
				districtCode
			};
		},
		//获取用户收货地址
		handleShipping() {
			// 判断用户是否登录
			const token = uni.getStorageSync('token')
			if (!token || !this.userInfo || !this.userInfo.userId) {
				// 未登录，跳转到登录页面
				uni.reLaunch({
					url: `/pages/auth/index?to_from=/pages/recycle/index`
				})
				return
			}

			const _this = this
			uni.chooseAddress({
				async success(res) {
					console.log('chooseAddress success', res);
					let telNumber = res.telNumber;
					if (telNumber == '020-81167888') {
						telNumber = "13912345678"
					}

					// 从regionTree获取各级的value（代码）
					const { provinceCode, cityCode, districtCode } = _this.getRegionCodes(
						res.provinceName,
						res.cityName,
						res.countyName
					);

					const payload = {
						province: res.provinceName,
						city: res.cityName,
						district: res.countyName,
						provinceCode: provinceCode,
						cityCode: cityCode,
						districtCode: districtCode,
						address: res.detailInfo,
						userName: res.userName,
						userPhone: telNumber,
					}
					_this.addressInfo = payload
					//  _this.loadRecycleMethod()

				},
				fail: err => {
					console.log('chooseAddress fail', err);
				}
			})
		},
		//点击日期
		handleDaysClick(day) {
			const _time = [
				day,
				this.timeMultiArray.find((item) => item.day === day).hour[0],
			];
			this.time = [..._time];
		},
		//点击时间
		handleHoursClick(hour) {
			const _time = [this.time[0], hour];
			this.time = [..._time];
			this.$refs["selectTimeRef"].onClose();

		},
		selectAddress() {

		},
		//格式化预约时间
		formatAppointTime() {
			const day = this.time[0]
			const hour = this.time[1]
			const appointEndTime = parseTime(day, "{y}-{m}-{d}") + " " + (parseInt(hour) + 2) + ":00:00"
			const appointStartTime = parseTime(day, "{y}-{m}-{d}") + " " + (parseInt(hour)) + ":00:00"
			return { appointEndTime, appointStartTime }
		},
		//点击省市区
		handleGeginClick() {
			this.$refs.gegionPicker.show()
		},
		selectTime() {
			this.$refs["selectTimeRef"].onOpen();
		},
		//省市区改变
		gegionPickerOnchange(e) {
			const { value } = e.detail
			const province = value[0].text
			const city = value[1].text
			const district = value[2].text
			const districtCode = value[2].value
			const address = ''
			this.address = address
			this.form = {
				...this.form,
				province,
				city,
				district,
				districtCode,
				address
			}
		},
		submitRecycle() {
			// console.log('-----提交订单----', this.evaluate)
			if (!this.addressInfo.address) {
				waitShowToast("请选择地址")
				return
			}
			uni.showLoading({ title: '加载中', mask: false })
			console.log("=======")
			const { appointEndTime, appointStartTime } = this.formatAppointTime()
			createClothesRecycleOrder({
				accountInfo: {
					accountName: this.addressInfo.userName,
					accountNumber: this.addressInfo.userPhone,
				},
				addressInfo: this.addressInfo,
				appointEndTime: appointEndTime,
				appointStartTime: appointStartTime,
				channel: "",
				extendInfo: {
					bonusId: 0,
					bonusPrice: 0,
					openId: this.openId,
				},
				weightRange: this.weightOptions[this.selectedWeight].range,
			}).then(({
				data,
				code
			}) => {
				uni.hideLoading()
				if (code === 200) {
					this.orderData = data || {};
					//提交成功，显示成功弹窗
					this.$refs.orderRef.onOpen()
				}
			}).catch(() => {
				uni.hideLoading()
			});
		},
		//点击订单详情
		handleOrder() {
			this.$refs.orderRef.onClose()
			const { orderNo } = this.orderData
			const url = `/pages/order/logistics-detail?orderNo=${orderNo}`
			uni.redirectTo({ url })
		},
	},
};
</script>

<style lang="scss" scoped>
.clothing-recycle {
	background: #f6f7f9 url("https://image.chushouya.com/assets/images/recycle/img_top.png") no-repeat top;
	background-size: 100% 488rpx;
	padding: 416rpx 32rpx 0;

	.recycle-top {
		width: 100%;
		height: 174rpx;
		background: #ffffff;
		border-radius: 24rpx;

		image {
			width: calc(100% - 44rpx);
			height: auto;
		}
	}

	.section-title {
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		font-size: 34rpx;
		color: #333333;
		margin-bottom: 8rpx;
	}

	.recycle-info {
		width: 100%;
		background: #ffffff;
		border-radius: 24rpx;
		margin-top: 24rpx;
		padding: 32rpx;

		/* Pickup Section */
		.pickup-section {
			.form-item {
				display: flex;
				align-items: center;
				height: 100rpx;
				border-bottom: 2rpx solid #eeeeee;

				.form-label {
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 28rpx;
					color: #333333;
					width: 160rpx;
				}

				.form-value {
					width: calc(100% - 160rpx);
					color: #333333;
					font-size: 28rpx;
					margin-right: 16rpx;

					.text {
						vertical-align: middle;
					}

					.placeholder {
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 28rpx;
						color: #a7abb2;
					}

					.arrow-icon {
						vertical-align: middle;
						width: 32rpx;
						height: 32rpx;
					}
				}
			}
		}

		/* Weight Section */
		.weight-section {
			margin-top: 30rpx;

			.section-title {
				margin-bottom: 24rpx;
			}
		}

		.weight-options {
			display: flex;
			justify-content: space-between;
			margin-bottom: 32rpx;
		}

		.weight-option {
			width: 23.15%;
			height: 160rpx;
			background: #f6f7f9;
			border-radius: 24rpx;
		}

		.weight-option.active {
			border: 4rpx solid #ffce46;
			background-color: #fff7e1;
		}

		.weight-range {
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 28rpx;
			color: #333333;
			margin-bottom: 6rpx;
		}

		.weight-price,
		.weight-note {
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 24rpx;
			color: #999999;
		}

		.environmental-impact {
			display: flex;
			align-items: center;
			background-color: #f0fff4;
			border-radius: 12rpx;
			padding: 16rpx 20rpx;
		}

		.eco-icon {
			width: 32rpx;
			height: 32rpx;
			margin-right: 12rpx;
		}

		.impact-text {
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 26rpx;
			color: #333333;

			text {
				color: #37c163;
			}
		}
	}

	.fixed-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		width: 100%;
		height: 160rpx;
		background: #ffffff;
		box-shadow: 0rpx -4rpx 8rpx 0rpx rgba(0, 0, 0, 0.02);
		padding: 32rpx;

		.btn {
			width: 100%;
			height: 96rpx;
			line-height: 96rpx;
			background: #ffce46;
			border-radius: 50rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 34rpx;
			color: #333333;
			text-align: center;
		}
	}
}
</style>
